<script setup lang="ts">
import { reactive, ref } from 'vue'
import md5 from 'js-md5'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { login } from '@/api/login'
import { useAppStore } from '@/stores/app'
// script here
const router = useRouter()
const state = reactive({
  rememberMe: false,
  loading: false
})
interface LoginForm {
  account: string
  password: string
}
const form = reactive<LoginForm>({
  account: '',
  password: ''
})

const rules = reactive<FormRules>({
  account: [{ required: true, message: '账号不能为空' }],
  password: [{ required: true, message: '密码不能为空' }]
})

const formRef = ref<FormInstance>()

function handleSubmit() {
  formRef.value!.validate((valid) => {
    if (valid) {
      handleLogin()
    }
  })
}

async function handleLogin() {
  state.loading = true

  try {
    const params: LoginForm = {
      account: form.account,
      password: md5(form.password)
    }
    const resp = await login(params)

    if (resp.access_token) {
      const store = useAppStore()
      store.setToken(resp.access_token)
      router.push('/')
    }
  } catch (err) {
    throw new Error('Login Error')
  } finally {
    state.loading = false
  }
}

const size = 'large'
</script>

<template>
  <el-config-provider :size="size">
    <el-form ref="formRef" :model="form" label-position="top" :rules="rules">
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="state.rememberMe" label="记住我" size="large" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          class="btn-login"
          :loading="state.loading"
          @click="handleSubmit"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </el-config-provider>
</template>

<style lang="scss" scoped>
// style here
.btn-login {
  width: 100%;
}
</style>
